package it.polimi.reTraveldream.eao;

import it.polimi.reTravelDream.dto.FlightDTO;
import it.polimi.reTravelDream.eao.FlightEAOLocal;
import it.polimi.reTraveldream.entities.Flight;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class FlightEAO
 */
@Stateless
public class FlightEAO implements FlightEAOLocal {

	@PersistenceContext
	private EntityManager em;
	
    public FlightEAO() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void addFlight(FlightDTO flightDTO) {
		Flight newFlight= new Flight(flightDTO);
		this.em.persist(newFlight);
		
		
	}

	@Override
	public List<FlightDTO> getAllFlights() {
		List<Flight> resultEntities= em.createNamedQuery(Flight.FIND_ALL, Flight.class)
                .getResultList();
		 List<FlightDTO> resultDTO= new ArrayList<FlightDTO>();
		 for (Flight h: resultEntities){
			 resultDTO.add(convertToDTO(h));
		 }
		 return resultDTO;
	}
	

	@Override
	public void removeFlight(FlightDTO currentFlight) {
		Flight flight=em.find(Flight.class, currentFlight.getId());	
		em.remove(flight);
	}

	@Override
	public void modifyFlight(FlightDTO currentFlight) {
		System.out.println("modify...");
		Flight flight=new Flight(currentFlight);
		em.merge(flight);
		System.out.println("in teoria merge fatto");
		
	}
	
	 private FlightDTO convertToDTO(Flight flightEntity) {
			FlightDTO flightDTO = new FlightDTO();
			flightDTO.setId(flightEntity.getId());
			flightDTO.setArrivalCity(flightEntity.getArrivalAirport());
			flightDTO.setDepartureCity(flightEntity.getDepartureAirport());
			flightDTO.setData(flightEntity.getDate());
			flightDTO.setPrice(flightEntity.getPrice());
			flightDTO.setActive(flightEntity.isActive());
			return flightDTO;
			
		}

}
